package com.hs.pk.berth.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hs.device.DetectorFeignClient;
import com.hs.common.api.dto.ResultCode;
import com.hs.common.api.dto.ResultVo;
import com.hs.pk.berth.bean.Berth;
import com.hs.pk.berth.bean.Road;
import com.hs.pk.berth.dto.AddBerthDto;
import com.hs.pk.berth.dto.RoadBerthDto;
import com.hs.pk.berth.service.IBerthService;
import com.hs.pk.berth.service.IRoadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * berth 前端控制器
 * </p>
 *
 * @author lhj
 * @since 2022-07-20
 */
@RestController
@RequestMapping("/berth")
@Api(tags = "泊车模块")
@Slf4j
public class BerthController {

    @Autowired
    private IBerthService berthService;
    @Autowired
    private IRoadService roadService;
    @Autowired
    private DetectorFeignClient detectorFeignClient;

    /**
     * 根据泊车号查询输出路段名称和泊位状态
     * @param id 泊车号
     * @return
     */
    @ApiOperation("根据泊位编号查询泊位状态和路段名称")
    @GetMapping("/{id}")
    public RoadBerthDto findParkingDtoByBerthId(
            @PathVariable("id") @ApiParam(name = "id",value = "泊位编号") Long id){
        RoadBerthDto roadBerthDto = berthService.findBerthDtoById(id);
        return roadBerthDto;
    }

    @ApiOperation("添加泊位")
    @PostMapping
    public ResultVo addBerth(@RequestBody @ApiParam(name = "addBerthDto",value = "添加泊位Dto") AddBerthDto addBerthDto){

        LambdaQueryWrapper<Road> qw = Wrappers.lambdaQuery(Road.class);
        qw.select(Road::getBerthNum);
        qw.eq(Road::getId,addBerthDto.getRoadId());
        Road road = roadService.getOne(qw);

        Berth berth = new Berth();
        BeanUtils.copyProperties(addBerthDto,berth);

        berth.setBerthName(road.getBerthNum() + "号泊位");
        berth.setStatus(0);
        boolean save = berthService.save(berth);
        log.info("berthId = {}",berth.getRoadId());

        //远程调用地磁模块
        detectorFeignClient.bindDevice(berth.getDetectorId(),berth.getId());

        if (save) {
            return new ResultVo(ResultCode.SUCCESS);
        }
        return new ResultVo(ResultCode.FAILED);
    }
}
